import Taro from "@tarojs/taro";

export const addCarts = goods => {
  const { goods_id, goods_model, goods_style, goods_number } = goods;
  let carts = Taro.getStorageSync('carts');

  if(carts !== '' && carts !== '[]') {
    carts = JSON.parse(carts);
  } else {
    carts = [];
  }

  let inCarts = false;
  carts = carts.map((item) => {
    if(`${goods_id}${goods_model}${goods_style}` === `${item.goods_id}${item.goods_model}${item.goods_style}`) {
      item.goods_number += goods_number;
      inCarts = true;
    }

    return item;
  });

  if(!inCarts) {
    carts.push(goods);
  }

  Taro.setStorageSync('carts', JSON.stringify(carts));
  Taro.showToast( {
    title: '加入成功',
    icon: 'success',
    duration: 1000
  });
};
